package com.guodefu.unifiedresponse.handler;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.guodefu.unifiedresponse.annotation.IgnoreUnifiedResponse;
import com.guodefu.unifiedresponse.entity.Response;
import lombok.SneakyThrows;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.core.MethodParameter;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.lang.NonNull;
import org.springframework.lang.Nullable;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;

/**
 * 统一响应封装
 * api 全局响应增强处理，将响应结果统一封装
 * 默认情况下该类及其子类未被实例化，则会实例化该类
 * 可以添加配置项；unified.response.enable=false,让此处的实例化失效
 * 若该类及其子类在别处已实例化，则此处不会实例化该类
 *
 * @author guodefu909
 **/
@RestControllerAdvice
@ConditionalOnMissingBean(value = GlobalResponseHandler.class)
@ConditionalOnProperty(prefix = "unified.response", value = "enable", havingValue = "true", matchIfMissing = true)
public class GlobalResponseHandler implements ResponseBodyAdvice<Object> {

    @Value("${spring.application.name:''}")
    private String appName;

    @Autowired
    public GlobalResponseHandler(ObjectMapper objectMapper) {
        this.objectMapper = objectMapper;
    }

    private final ObjectMapper objectMapper;

    @Override
    public boolean supports(@NonNull MethodParameter returnType,
                            @NonNull Class<? extends HttpMessageConverter<?>> converterType) {
        // 方法上如果标注了忽略统一响应注解，不进行处理
        return !returnType.hasMethodAnnotation(IgnoreUnifiedResponse.class);
    }

    @SneakyThrows
    @Override
    public Object beforeBodyWrite(@Nullable Object body,
                                  @NonNull MethodParameter returnType,
                                  @NonNull MediaType selectedContentType,
                                  @NonNull Class<? extends HttpMessageConverter<?>> selectedConverterType,
                                  @NonNull ServerHttpRequest request,
                                  @NonNull ServerHttpResponse response) {
        if (returnType.getParameterType() == Response.class) {
            return body;
        }
        // 将响应结果封装成统一响应体
        Response<Object> responseResult = Response.success(appName, body);
        // 返回类型是 String：不能直接返回，需要进行额外处理
        if (returnType.getParameterType() == String.class) {
            // 1. 将 Content-Type 设为 application/json; 返回类型是 String 时，默认 Content-Type = text/plain
            // 2. 将结果转为 Json 字符串再返回
            // 不转回 String 会报错： java.lang.ClassCastException: xxx cannot be cast to java.lang.String
            HttpHeaders headers = response.getHeaders();
            headers.setContentType(MediaType.APPLICATION_JSON);
            return objectMapper.writeValueAsString(responseResult);
        }
        return responseResult;
    }

}
